package Organizationgroup

import (
	"context"

	v1 "gitee.com/liangziyisheng/caas-platform-mc/api/organization/v1"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/consts"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/dao"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/service"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
)

type sOrganization struct{}

var l = g.Log("logger for Organization")

func New() *sOrganization {
	return &sOrganization{}
}

func init() {
	l.SetFlags(glog.F_FILE_LONG)
	service.RegisterOrganization(New())
}

func (s *sOrganization) List(ctx context.Context, in *v1.ListInput) (out *v1.ListOutput, err error) {
	cls := dao.Organization.Columns()
	out = &v1.ListOutput{}
	err = dao.Organization.Ctx(ctx).Where(cls.TenantCode, in.TenantCode).Scan(&out.Data)
	// err = md.Limit((in.Page-1)*in.Size, in.Size).ScanAndCount(&out.Data, &out.Total, true)
	if err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.ListFailed, in))
	}
	return out, nil
}

func (s *sOrganization) Add(ctx context.Context, in *v1.AddInput) (out *v1.AddOutput, err error) {
	id, err := dao.Organization.Ctx(ctx).InsertAndGetId(in.Organization)
	if err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.AddFailed, in.Organization))
	}
	return &v1.AddOutput{Id: id}, nil
}

func (s *sOrganization) Delete(ctx context.Context, in *v1.DeleteInput) (out *v1.DeleteOutput, err error) {
	// 先检查是否存在用户关联
	us, err := dao.GroupUser.Ctx(ctx).Where(dao.GroupUser.Columns().GroupId, in.Id).Count()
	if err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.QueryOrganizationFailed, in.Id))
	}
	if us > 0 {
		return nil, gerror.NewCode(consts.UserAssignedInGroup)
	}

	rs, err := dao.Organization.Ctx(ctx).Where(dao.Organization.Columns().Id, in.Id).Delete()
	if err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.DeleteFailed, in.Id))
	}
	out = &v1.DeleteOutput{}
	if out.Rows, err = rs.RowsAffected(); err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.DeleteFailed, in.Id))
	}
	if out.Rows == 0 {
		return nil, gerror.NewCode(gcode.WithCode(consts.DeleteFailed, in.Id))
	}
	return out, nil
}

func (s *sOrganization) Update(ctx context.Context, in *v1.UpdateInput) (out *v1.UpdateOutput, err error) {
	out = &v1.UpdateOutput{}
	out.Rows, err = dao.Organization.Ctx(ctx).Data(in.Organization).Where(dao.Organization.Columns().Id, in.Id).UpdateAndGetAffected()
	if err != nil {
		l.Error(ctx, err)
		return nil, gerror.NewCode(gcode.WithCode(consts.UpdateFailed, in.Organization))
	}
	if out.Rows == 0 {
		return nil, gerror.NewCode(gcode.WithCode(consts.UpdateFailed, in.Id))
	}
	return out, nil
}
